// 系统参数设置模块
class SystemParamsManager {
    static params = [
        { id: 1, name: '系统名称', code: 'system.name', value: '智能教育系统', type: '字符串', description: '系统显示名称', status: 'active' },
        { id: 2, name: '会话超时时间', code: 'session.timeout', value: '30', type: '整数', description: '用户会话超时时间(分钟)', status: 'active' },
        { id: 3, name: '密码策略', code: 'password.policy', value: 'medium', type: '枚举', description: '密码强度策略', status: 'active' },
        { id: 4, name: '默认语言', code: 'system.language', value: 'zh-CN', type: '枚举', description: '系统默认语言', status: 'active' }
    ];

    static loadContent(container) {
        container.innerHTML = `
            <div class="description">
                配置系统运行所需的各项参数，包括系统名称、Logo、默认设置等。
            </div>
            
            <div class="actions">
                <button class="btn btn-primary btn-add-param"><i class="fas fa-plus"></i> 新增参数</button>
                <button class="btn btn-default btn-edit-param-batch"><i class="fas fa-edit"></i> 修改参数</button>
                <button class="btn btn-danger btn-delete-param-batch"><i class="fas fa-trash"></i> 删除参数</button>
                <div class="search-area">
                    <input type="text" placeholder="搜索参数...">
                    <button><i class="fas fa-search"></i> 搜索</button>
                </div>
            </div>
            
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAllParams"></th>
                            <th>参数名称</th>
                            <th>参数代码</th>
                            <th>参数值</th>
                            <th>参数类型</th>
                            <th>描述</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>系统名称</td>
                            <td>system.name</td>
                            <td>智能教育系统</td>
                            <td>字符串</td>
                            <td>系统显示名称</td>
                            <td><button class="status-btn active">启用</button></td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>会话超时时间</td>
                            <td>session.timeout</td>
                            <td>30</td>
                            <td>整数</td>
                            <td>用户会话超时时间(分钟)</td>
                            <td><button class="status-btn active">启用</button></td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>密码策略</td>
                            <td>password.policy</td>
                            <td>medium</td>
                            <td>枚举</td>
                            <td>密码强度策略</td>
                            <td><button class="status-btn active">启用</button></td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>默认语言</td>
                            <td>system.language</td>
                            <td>zh-CN</td>
                            <td>枚举</td>
                            <td>系统默认语言</td>
                            <td><button class="status-btn active">启用</button></td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="pagination">
                <a href="#">上一页</a>
                <a href="#" class="active">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#">4</a>
                <a href="#">5</a>
                <a href="#">下一页</a>
            </div>
        `;

        // 设置全选功能
        mainManager.setupSelectAll('selectAllParams', 'rowCheckbox');

        // 设置操作按钮事件
        systemManager.setupActionButtons(container);

        // 新增参数按钮
        const addParamBtn = container.querySelector('.btn-add-param');
        if (addParamBtn) {
            addParamBtn.addEventListener('click', () => {
                AddParamModal.showModal();
            });
        }

        // 编辑和删除按钮（事件委托）
        const tableBody = container.querySelector('.table-container tbody');
        if (tableBody) {
            tableBody.addEventListener('click', (e) => {
                const editButton = e.target.closest('.operation a:first-child');
                if (editButton) {
                    e.preventDefault();
                    const row = editButton.closest('tr');
                    if (row) {
                        const paramData = {
                            id: row.rowIndex,
                            name: row.cells[1].textContent,
                            code: row.cells[2].textContent,
                            value: row.cells[3].textContent,
                            type: row.cells[4].textContent,
                            description: row.cells[5].textContent,
                            status: row.cells[6].querySelector('.status-btn').classList.contains('active') ? 'active' : 'inactive'
                        };
                        EditParamModal.showModal(paramData);
                    }
                }

                const deleteButton = e.target.closest('.operation a:nth-child(2)');
                if (deleteButton) {
                    e.preventDefault();
                    const row = deleteButton.closest('tr');
                    if (row) {
                        const paramName = row.cells[1].textContent;
                        SystemParamsManager.showDeleteConfirm(paramName, () => {
                            alert('删除参数成功');
                            SystemParamsManager.loadContent(container);
                        });
                    }
                }
            });
        }

        // 设置搜索功能
        const searchButton = container.querySelector('.search-area button');
        if (searchButton) {
            searchButton.addEventListener('click', () => {
                systemManager.search('system-params');
            });
        }
    }

    // 显示删除确认弹窗
    static showDeleteConfirm(paramName, onConfirm) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h3>删除确认</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <div style="padding: 20px; font-size: 16px; color: #333;">
                    确定要删除参数"${paramName}"吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" id="delete-cancel-btn">取消</button>
                    <button type="button" class="btn btn-danger" id="delete-confirm-btn">确认删除</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#delete-cancel-btn');
        const confirmBtn = modal.querySelector('#delete-confirm-btn');
        const overlay = modal.querySelector('.modal-overlay');

        const closeModal = () => {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        };

        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', closeModal);
        confirmBtn.addEventListener('click', () => {
            onConfirm();
            closeModal();
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeModal();
        });

        setTimeout(() => modal.classList.add('show'), 10);
    }
}

// 新增参数模态框
class AddParamModal {
    static showModal() {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'addParamModal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>新增参数</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="add-param-form">
                    <div class="form-group">
                        <label for="param-name">参数名称 <span class="required">*</span></label>
                        <input type="text" id="param-name" name="name" class="form-control" required>
                        <div class="error-text" id="param-name-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="param-code">参数代码 <span class="required">*</span></label>
                        <input type="text" id="param-code" name="code" class="form-control" placeholder="例如: system.name" required>
                        <div class="error-text" id="param-code-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="param-value">参数值 <span class="required">*</span></label>
                        <input type="text" id="param-value" name="value" class="form-control" required>
                        <div class="error-text" id="param-value-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="param-type">参数类型 <span class="required">*</span></label>
                        <select id="param-type" name="type" class="form-control" required>
                            <option value="">请选择</option>
                            <option value="字符串">字符串</option>
                            <option value="整数">整数</option>
                            <option value="枚举">枚举</option>
                            <option value="布尔">布尔</option>
                        </select>
                        <div class="error-text" id="param-type-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="param-description">描述</label>
                        <textarea id="param-description" name="description" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="param-status">状态 <span class="required">*</span></label>
                        <select id="param-status" name="status" class="form-control" required>
                            <option value="active">启用</option>
                            <option value="inactive">禁用</option>
                        </select>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="save-btn" disabled>保存</button>
                    </div>
                </form>
            </div>
        `;
        document.body.appendChild(modal);
        this.initEvents(modal);
        setTimeout(() => modal.classList.add('show'), 10);
    }

    static initEvents(modal) {
        const form = modal.querySelector('.add-param-form');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#cancel-btn');
        const overlay = modal.querySelector('.modal-overlay');

        closeBtn.addEventListener('click', () => this.closeModal(modal));
        cancelBtn.addEventListener('click', () => this.closeModal(modal));
        overlay.addEventListener('click', () => this.closeModal(modal));
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') this.closeModal(modal);
        });

        this.initFormValidation(form);
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.submitForm(form);
        });
    }

    static initFormValidation(form) {
        const fields = ['name', 'code', 'value', 'type'];
        fields.forEach(field => {
            const input = form[field];
            input.addEventListener('input', () => {
                this.validateField(field, input.value);
                this.checkFormValidity(form);
            });
            input.addEventListener('blur', () => {
                this.validateField(field, input.value);
            });
        });
    }

    static validateField(field, value) {
        const errorElement = document.getElementById(`param-${field}-error`);
        let errorMessage = '';

        if (!value.trim()) {
            errorMessage = '此字段不能为空';
        } else if (field === 'code' && !/^[a-z]+\.[a-z]+$/.test(value)) {
            errorMessage = '参数代码格式错误，应为：模块.参数';
        }

        errorElement.textContent = errorMessage;
        return !errorMessage;
    }

    static checkFormValidity(form) {
        const fields = ['name', 'code', 'value', 'type'];
        const allValid = fields.every(field => {
            const value = form[field].value;
            return this.validateField(field, value);
        });
        form.querySelector('#save-btn').disabled = !allValid;
    }

    static submitForm(form) {
        const saveBtn = form.querySelector('#save-btn');
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;

        const formData = {
            name: form.name.value,
            code: form.code.value,
            value: form.value.value,
            type: form.type.value,
            description: form.description.value,
            status: form.status.value
        };

        setTimeout(() => {
            SystemParamsManager.params.push({
                id: SystemParamsManager.params.length + 1,
                ...formData
            });
            alert('新增参数成功');
            this.closeModal(document.getElementById('addParamModal'));
            const contentContainer = document.getElementById('system-params');
            if (contentContainer) {
                SystemParamsManager.loadContent(contentContainer);
            }
        }, 1000);
    }

    static closeModal(modal) {
        modal.classList.remove('show');
        setTimeout(() => modal.remove(), 300);
    }
}

// 编辑参数模态框
class EditParamModal {
    static showModal(paramData) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'editParamModal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>编辑参数</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="edit-param-form">
                    <div class="form-group">
                        <label for="edit-param-name">参数名称 <span class="required">*</span></label>
                        <input type="text" id="edit-param-name" name="name" class="form-control" value="${paramData.name}" required>
                        <div class="error-text" id="edit-param-name-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-param-code">参数代码 <span class="required">*</span></label>
                        <input type="text" id="edit-param-code" name="code" class="form-control" value="${paramData.code}" disabled>
                        <div class="error-text" id="edit-param-code-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-param-value">参数值 <span class="required">*</span></label>
                        <input type="text" id="edit-param-value" name="value" class="form-control" value="${paramData.value}" required>
                        <div class="error-text" id="edit-param-value-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-param-type">参数类型 <span class="required">*</span></label>
                        <select id="edit-param-type" name="type" class="form-control" required>
                            <option value="字符串" ${paramData.type === '字符串' ? 'selected' : ''}>字符串</option>
                            <option value="整数" ${paramData.type === '整数' ? 'selected' : ''}>整数</option>
                            <option value="枚举" ${paramData.type === '枚举' ? 'selected' : ''}>枚举</option>
                            <option value="布尔" ${paramData.type === '布尔' ? 'selected' : ''}>布尔</option>
                        </select>
                        <div class="error-text" id="edit-param-type-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-param-description">描述</label>
                        <textarea id="edit-param-description" name="description" class="form-control" rows="3">${paramData.description}</textarea>
                    </div>
                    <div class="form-group">
                        <label for="edit-param-status">状态 <span class="required">*</span></label>
                        <select id="edit-param-status" name="status" class="form-control" required>
                            <option value="active" ${paramData.status === 'active' ? 'selected' : ''}>启用</option>
                            <option value="inactive" ${paramData.status === 'inactive' ? 'selected' : ''}>禁用</option>
                        </select>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="save-btn">保存</button>
                    </div>
                </form>
            </div>
        `;
        document.body.appendChild(modal);
        this.initEvents(modal, paramData);
        setTimeout(() => modal.classList.add('show'), 10);
    }

    static initEvents(modal, paramData) {
        const form = modal.querySelector('.edit-param-form');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#cancel-btn');
        const overlay = modal.querySelector('.modal-overlay');

        closeBtn.addEventListener('click', () => this.closeModal(modal));
        cancelBtn.addEventListener('click', () => this.closeModal(modal));
        overlay.addEventListener('click', () => this.closeModal(modal));
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') this.closeModal(modal);
        });

        this.initFormValidation(form);
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.submitForm(form, paramData);
        });
    }

    static initFormValidation(form) {
        const fields = ['name', 'value', 'type'];
        fields.forEach(field => {
            const input = form[field];
            input.addEventListener('input', () => {
                this.validateField(field, input.value);
                this.checkFormValidity(form);
            });
        });
    }

    static validateField(field, value) {
        const errorElement = document.getElementById(`edit-param-${field}-error`);
        let errorMessage = '';

        if (!value.trim()) {
            errorMessage = '此字段不能为空';
        }

        errorElement.textContent = errorMessage;
        return !errorMessage;
    }

    static checkFormValidity(form) {
        const fields = ['name', 'value', 'type'];
        const allValid = fields.every(field => {
            const value = form[field].value;
            return this.validateField(field, value);
        });
        form.querySelector('#save-btn').disabled = !allValid;
    }

    static submitForm(form, paramData) {
        const saveBtn = form.querySelector('#save-btn');
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;

        const formData = {
            name: form.name.value,
            value: form.value.value,
            type: form.type.value,
            description: form.description.value,
            status: form.status.value
        };

        setTimeout(() => {
            const param = SystemParamsManager.params.find(p => p.id === paramData.id);
            if (param) {
                Object.assign(param, formData);
            }
            alert('编辑参数成功');
            this.closeModal(document.getElementById('editParamModal'));
            const contentContainer = document.getElementById('system-params');
            if (contentContainer) {
                SystemParamsManager.loadContent(contentContainer);
            }
        }, 1000);
    }

    static closeModal(modal) {
        modal.classList.remove('show');
        setTimeout(() => modal.remove(), 300);
    }
}